import { useModel, history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import type { PatrolDeviceTableItem } from './types.d';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { ProTable } from '@ant-design/pro-components';
import { queryPatrolDevices, removePatrolDevice } from './service';
import PatrolExpandDetail from './components/PatrolExpandDetail';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import CreatePatrolDevice from './components/CreatePatrolDevice';
import UpdatePatrolDevice from './components/UpdatePatrolDevice';
import ConfirmModal from '@/components/ConfirmModal';
import ExportModal from './components/ExportModal';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.patrolDevice || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);
  const ifExport = auths.has(Auths.EXPORT);
  const batchTaskAuth = currUser?.auth ? new Set(currUser.auth.batchTask || []) : new Set();
  const readBatchTask = batchTaskAuth.has(Auths.READ);
  const subTitleContent = (
    <span>
      巡检设备列表，如需批量添加巡检列表，请前往
      {readBatchTask ? (
        <a
          onClick={() => {
            history.push('/batch-task');
          }}
        >
          批量任务
        </a>
      ) : (
        '批量任务'
      )}
    </span>
  );
  const columns: ProColumns<PatrolDeviceTableItem>[] = [
    {
      title: 'id',
      dataIndex: '_id',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
      width: 150,
    },
    {
      title: '巡检设备编号',
      dataIndex: 'deviceSn',
      hideInForm: true,
      align: 'center',
      width: 150,
      render: (_, record) => (
        <a
          onClick={() => {
            // history.push(`/device/patrol/more/${record.deviceSn}`);
            history.push({
              pathname: '/device/patrol/more',
              state: record.deviceSn,
            });
          }}
        >
          {record.deviceSn}
        </a>
      ),
    },
    {
      title: '当前坐标',
      width: 240,
      align: 'center',
      dataIndex: 'coordinate',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => {
        const coord = record.coordinate || [];
        const longtiude = `${coord[0] || 0}`;
        const latitude = `${coord[1] || 0}`;
        return `${longtiude.slice(0, 12)}, ${latitude.slice(0, 12)}`;
      },
    },
    {
      title: '流量卡号',
      width: 220,
      dataIndex: 'iccid',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      width: 180,
    },
    {
      title: '最新刷新时间',
      dataIndex: 'refreshTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      width: 180,
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) =>
        ifModify || ifDelete
          ? [
              ifModify && (
                <UpdatePatrolDevice reload={() => action?.reload()} currPatrol={record} />
              ),
              ifDelete && (
                <ConfirmModal
                  reload={() => action?.reload()}
                  operFunc={async () => await removePatrolDevice(record._id)}
                  text={`是否确定删除巡检设备(${record.deviceSn})`}
                />
              ),
              // <a
              //   onClick={() => {
              //     // history.push(`/device/patrol/more/${record.deviceSn}`);
              //     history.push({
              //       pathname: '/device/patrol/more',
              //       state: record.deviceSn,
              //     });
              //   }}
              // >
              //   详情
              // </a>,
            ]
          : [<PlaceHolderCpn key={record._id} />],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: subTitleContent,
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            {
              path: '/device',
              breadcrumbName: '设备管理',
            },
            {
              path: '/device/patrol',
              breadcrumbName: '巡检设备',
            },
          ],
        },
      }}
    >
      <ProTable<PatrolDeviceTableItem>
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        rowKey="_id"
        columnEmptyText="暂无数据"
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryPatrolDevices(param, sort);
          return res;
        }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        expandable={{ expandedRowRender: (record) => <PatrolExpandDetail patrolDevice={record} /> }}
        toolBarRender={(action) => [
          ifCreate && <CreatePatrolDevice reload={() => action?.reload()} />,
          ifExport && <ExportModal />,
        ]}
      />
    </PageHeaderWrapper>
  );
};
